#include <QFormLayout>
#include <QDirModel>

#include "HelpBrowser.h"
#include "HelpSelectDialog.h"
#include "ui_HelpBrowser.h"

HelpBrowser::HelpBrowser(QWidget *parent) :
    QMainWindow(parent),
    m_ui(new Ui::HelpBrowser)
{
    helpEngine = new QHelpEngine("help.qhc");
    helpEngine->setupData();
    m_ui->setupUi(this);
    filter = new QLineEdit();
    filter->setStyleSheet("margin: 5px;");
    label = new QLabel("Look for: ");
    label->setStyleSheet("margin: 5px");
    setCentralWidget(m_ui->mainLayoutWidget);
    QObject::connect(filter, SIGNAL(textChanged(QString)), SLOT(filterChanged(QString)));
    m_ui->indexLayout->addWidget(label, 0, 0, 1, 1);
    m_ui->indexLayout->addWidget(filter, 0, 1, 1, 1);
    m_ui->indexLayout->addWidget(helpEngine->indexWidget(), 1, 0, 1, 2);
    m_ui->indexDockContents->setLayout(m_ui->indexLayout);
    m_ui->contentLayout->addWidget(helpEngine->contentWidget());
    m_ui->contentDockContents->setLayout(m_ui->contentLayout);
    tabifyDockWidget(m_ui->contentDock, m_ui->indexDock);
    m_ui->contentDock->raise();
    m_ui->textBrowser->setHelpEngine(helpEngine);
    QObject::connect(helpEngine->contentWidget(), SIGNAL(doubleClicked(QModelIndex)), SLOT(changeContent(QModelIndex)));
    QObject::connect(helpEngine->indexWidget(), SIGNAL(doubleClicked(QModelIndex)), SLOT(changeContent(QModelIndex)));
    changeUrl(QUrl("qthelp://lbanimatorstudio2/doc/index.htm"));
}

HelpBrowser::~HelpBrowser()
{
    delete helpEngine;
    delete m_ui;
}

void HelpBrowser::changeEvent(QEvent *e)
{
    QMainWindow::changeEvent(e);
    switch (e->type())
	{
		case QEvent::LanguageChange:
			m_ui->retranslateUi(this);
			break;
		default:
			break;
    }
}

void HelpBrowser::changeContent(const QModelIndex &idx)
{
    if (qobject_cast<QHelpContentWidget *>(sender()) != NULL)
	{
        changeUrl(helpEngine->contentModel()->contentItemAt(idx)->url());
	}
    else if (qobject_cast<QHelpIndexWidget *>(sender()) != NULL)
    {
        const QMap<QString, QUrl>& map = helpEngine->indexModel()->linksForKeyword(idx.data().toString());
        if (map.size() == 1)
        {
            changeUrl(map.begin().value());
        }
        else if (map.size() > 1)
        {
            HelpSelectDialog select(map, idx.data().toString(), this);
            if (select.exec() == 1)
            {
                changeUrl(select.getSelectedUrl());
            }
        }
    }
}

void HelpBrowser::changeUrl(const QUrl &url)
{
    m_ui->textBrowser->setSource(url);
}

void HelpBrowser::filterChanged(const QString &filter)
{
    helpEngine->indexWidget()->filterIndices(filter, filter);
}
